package com.lxq.LeetCode.isHappy;

import java.util.Arrays;
import java.util.HashSet;

public class Solution {
    public static void main(String[] args) {
        System.out.println(isHappy(19));
    }

    public static boolean isHappy(int n) {
        HashSet<Integer> hs = new HashSet<Integer>();
        int[] num = num2arr(n);

        while (arrSum(num) != 1) {
            if (hs.contains(n)){
                return false;
            }else{
                hs.add(n);
            }
            n = arrPow(num);
            num = num2arr(n);
        }
        return true;
    }

    // 数 -> 数组
    public static int[] num2arr(int a) {
        int[] num = new int[10];
        String s = String.valueOf(a);
        for (int i = 0; i < s.length(); i++) {
            num[i] = s.charAt(i) - '0';
        }
//        System.out.println(Arrays.toString(num));
        return num;
    }

    // 数组每位数字求和
    public static int arrSum(int[] num) {
        int sum = 0;
        for (int j : num) {
            sum += j;
        }
        return sum;
    }

    // 数组每位数字求平方求和
    public static int arrPow(int[] num){
        int sum = 0;
        for (int j : num) {
            sum += Math.pow(j,2);
        }
        return sum;
    }
}
